<?php
/**
 * Created by PhpStorm.
 * User: Vagrant Archer
 * Date: 2017/7/19
 * Time: 22:16
 */

require_once "Classes/AfterImage.php";
include "ObserverFactoryClass.php";
include "constant.php";
include "ObserverList.php";
include "log4php/Logger.php";
include "WechatSend.php";


date_default_timezone_set('PRC');
Logger::configure(dirname(__FILE__).'/logger.xml');
$logger = Logger::getLogger('myLogger');


$observerList		=	array();
$observerFactory    =   new ObserverFactory();


echo "\"They shall not pass.  --- Heimdall\"\n";

if($argc < 2)
{
	echo "Observer Group Number is mandatory.";
	exit(0);
}

if ("TEST" == $argv[1]) {
    batchTest();
    exit();
}

if (!is_numeric($argv[1])) {
	echo "Observer Group Number is required, but {$argv[1]} provides.";
	exit(0);
}

if (!isset($observerInList[$argv[1]])) {
	echo "Observer Group Number {$argv[1]} not existed.";
	exit(0);
}


//Initial the Observer Factory
foreach ($observerInList[$argv[1]] as $inObserverList) {
	array_push($observerList, $observerFactory->createObserver($inObserverList));
}


//Loop to observe
while(1)
{
	foreach($observerList as $myObserver)
	{
		$myAfterImage =   $myObserver->observe();
		simpleOutputSite($myAfterImage);
        unset($myAfterImage);
	}
	echo "=====================\n";

	sleep(5);
}

exit(0);


/**
 * @param AfterImage $inAfterImage
 */
function simpleOutputSite(AfterImage $inAfterImage)
{
	$normalLogger   =   Logger::getLogger('myLogger');
	$eventLogger    =   Logger::getLogger('event');
	if($inAfterImage->isAiStatus())
	{
		if ($inAfterImage->getAiElapsedTime() < __PARAM_HTTP_TIMELONG__) {
			$message    =   "{$inAfterImage->getAiName()}　：{$inAfterImage->getAiElapsedTime()}\n";
			echo date("H:i:s", time()).$message;
			$normalLogger->info($message);
		}
		else{
			$message    =   "警告：{$inAfterImage->getAiName()}　状态：缓慢：{$inAfterImage->getAiElapsedTime()}\n";
			echo date("H:i:s", time()).$message;
			$eventLogger->warn($message);
            if (__MESSENGER_TYPE_WECHAT__ == $inAfterImage->getAiAlertType()) {
                $wechatMessage = date("H:i:s", $inAfterImage->getAiTime()) . $inAfterImage->getAiName() . "【缓慢】" . $inAfterImage->getAiElapsedTime();
                sendWeChatMessage($wechatMessage);
            }

		}
	}
	else
	{
		$errMessage = join(":", $inAfterImage->getAiReturnCode());
		$message    =   "警告：{$inAfterImage->getAiName()}　状态：异常！！！{$errMessage}\n";
		echo date("Y-m-d.H:i:s", time()).$message;
		$eventLogger->error($message);
        if (__MESSENGER_TYPE_WECHAT__ == $inAfterImage->getAiAlertType()) {
            $wechatMessage = date("H:i:s", $inAfterImage->getAiTime()) . $inAfterImage->getAiName() . "【异常】" . $errMessage;
//            echo "\n\n单笔通知内容：{$wechatMessage}\n\n";
            sendWeChatMessage($wechatMessage);
        }
	}

}

function batchTest()
{
    sendWeChatMessage("试音123456");
}



?>